package com.lanou.zakerproject.subscribe;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lanou.zakerproject.base.BaseActivity;
import com.lanou.zakerproject.R;
import com.lanou.zakerproject.base.DayNightMode;
import com.lanou.zakerproject.base.VolleySingleton;
import com.lanou.zakerproject.city.CityActivity;
import com.lanou.zakerproject.community.CommunityFragment;
import com.lanou.zakerproject.disport.DisportFragment;
import com.lanou.zakerproject.hotspot.HotspotFragment;
import com.lanou.zakerproject.hotspot.HotspotLikeActivity;
import com.lanou.zakerproject.person.PersonActivity;
import com.lanou.zakerproject.splash.SplashActivity;
import com.lanou.zakerproject.tool.DataCleanManager;
import com.lanou.zakerproject.tool.GsonRequest;

import java.util.ArrayList;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ArrayList<Fragment> datas;
    private MainAdapter mainAdapter;
    private DayNightMode dayNightMode;
    private DrawerLayout drawer;
    private LinearLayout drawerHead;
    private GestureDetector mGestureDetector;
    private DataCleanManager dataCleanManager;

    private ImageView cover_img, cover_down;
    private String URL = "http://iphone.myzaker.com/zaker/cover.php?_appid=AndroidPhone&_bsize=1080_1920&_dev=97&_lat=4.9E-324&_lng=4.9E-324&_mcode=D79B3480&_net=wifi&_nudid=7891a15eb7d34771&_os=5.1_GoogleNexus5-5.1.0-API22-1080x1920&_os_name=GoogleNexus5-5.1.0-API22-1080x1920&_udid=7891a15eb7d34771&_v=6.4.5&_version=6.44&api_version=3.3";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);//ShareSDK初始化
        //在Activity开始初始化视图前去应用才能生效
        DayNightMode.onActivityCreateSetTheme(this);
        setContentView(R.layout.panelswitcher_homepage);


        PanelSwitcher panelSwitcher = (PanelSwitcher) findViewById(R.id.panelswitch);
        panelSwitcher.setLongClickable(true);
        View cover = LayoutInflater.from(this).inflate(R.layout.activity_cover, null);
        View bottom = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        panelSwitcher.setAboveView(cover);
        panelSwitcher.setBehindView(bottom);

        cover_img = (ImageView) cover.findViewById(R.id.cover_img);
        cover_down = (ImageView) cover.findViewById(R.id.cover_down);
        getRequsetData(URL);

        viewPager = (ViewPager) bottom.findViewById(R.id.viewPager_main);
        tabLayout = (TabLayout) bottom.findViewById(R.id.community_tablayout);

        toolbar = (Toolbar) bottom.findViewById(R.id.toolbar_subscribe);
        toolbar.setTitle("订阅");
//        toolbar.setSubtitle("1");
//        toolbar.setLogo(R.mipmap.icon);
        setSupportActionBar(toolbar);
//        setNavigationIcon需要放在 setSupportActionBar之后才会生效。
//        toolbar.setNavigationIcon(R.mipmap.icon_topic_tab);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);

        drawer = (DrawerLayout) bottom.findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        drawerHead = (LinearLayout) findViewById(R.id.nav_head);
        drawerHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, PersonActivity.class);
                startActivity(intent);
            }
        });

        datas = new ArrayList<>();
        datas.add(new SubscribeFragment());
        datas.add(new HotspotFragment());
        datas.add(new DisportFragment());
        datas.add(new CommunityFragment());

        mainAdapter = new MainAdapter(getSupportFragmentManager(), datas, this);
        viewPager.setAdapter(mainAdapter);
        tabLayout.setupWithViewPager(viewPager);

        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(mainAdapter.getTabView(i));

            }
        }
//        invalidateOptionsMenu();
        //根据viewPager 变换 去判断menu
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Menu menu = toolbar.getMenu();
                menu.findItem(R.id.action_find).setVisible(false);
                menu.findItem(R.id.action_tags).setVisible(false);
                menu.findItem(R.id.action_city).setVisible(false);
                switch (position) {
                    case 0:
                        toolbar.setTitle("订阅");
                        menu.findItem(R.id.action_find).setVisible(true);
                        break;
                    case 1:
                        toolbar.setTitle("热点");
                        menu.findItem(R.id.action_tags).setVisible(true);
                        break;
                    case 2:
                        toolbar.setTitle("玩乐");
                        menu.findItem(R.id.action_city).setVisible(true);
                        break;
                    case 3:
                        toolbar.setTitle("社区");
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });


//给tabhost做监听，更改toolbar显示
//        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
//            @Override
//            public void onTabChanged(String tabId) {
//
//                    toolbar.setTitle("订阅");
//                    isMenuShuffle = 0;
//                } else if (tabId.equals("tab_hotspot")) {
//                    toolbar.setTitle("热点");
//                    isMenuShuffle = 1;
//                } else if (tabId.equals("tab_disport")) {
//                    toolbar.setTitle("玩乐");
//                    isMenuShuffle = 2;
//                } else {
//                    toolbar.setTitle("社区");
//                    isMenuShuffle = 3;
//                }
//                Log.d("MainActivity", "isMenuShuffle:" + isMenuShuffle);
//            }
//        });

    }


    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            Intent intent = new Intent();
            switch (menuItem.getItemId()) {
                case R.id.action_find:
                    intent.setClass(MainActivity.this, SearchActivity.class);
                    startActivity(intent);
                    break;
                case R.id.action_tags:
                    intent.setClass(MainActivity.this, HotspotLikeActivity.class);
                    startActivity(intent);
                    break;
                case R.id.action_city:
                    intent.setClass(MainActivity.this, CityActivity.class);
                    startActivity(intent);
                    break;
                case R.id.action_person:
                    drawer.openDrawer(GravityCompat.END);
                    break;
            }
            return true;
        }
    };

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.END)) {
            drawer.closeDrawer(GravityCompat.END);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_subscribe, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        switch (isMenuShuffle) {
//            case 0:
//                menu.findItem(R.id.action_find).setVisible(true);
//                break;
//            case 1:
//                menu.findItem(R.id.action_tags).setVisible(true);
//                break;
//            case 2:
//                menu.findItem(R.id.action_city).setVisible(true);
//                break;
//            default:
//                break;
//        }

//        return super.onPrepareOptionsMenu(menu);
//    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
        // Handle navigation view item clicks here.
        int id = menuItem.getItemId();

        if (id == R.id.nav_theme) {
            // Handle the camera action
            toast("主题切换");
        } else if (id == R.id.nav_pic) {
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
            try {
                builder.setTitle("缓存大小"+dataCleanManager.getTotalCacheSize(this));
            } catch (Exception e) {
                e.printStackTrace();
            }
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dataCleanManager.clearAllCache(MainActivity.this);
                    try {
                        Toast.makeText(MainActivity.this, "缓存大小" + dataCleanManager.getTotalCacheSize(MainActivity.this), Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            builder.show();

        } else if (id == R.id.nav_mode) {
            toast("夜间模式切换");
            dayNightMode.changeToTheme(this);
        } else if (id == R.id.nav_font) {
            toast("改变正文字号");
        } else if (id == R.id.nav_share) {
            showShare();
        }
        drawer.closeDrawer(GravityCompat.END);
        return true;
    }


    /**
     * 解析数据的方法
     *
     * @param urls 接口
     */
    private void getRequsetData(String urls) {
        GsonRequest<CoverData> gsonRequest = new GsonRequest<>(urls, CoverData.class, new Response.Listener<CoverData>() {
            @Override
            public void onResponse(CoverData response) {
                ImageLoader.ImageListener listener = ImageLoader.getImageListener(cover_img, R.mipmap.iconfont_picpng, R.mipmap.default_img_nonet);
                VolleySingleton.getImageLoader().get(response.getData().getPic(), listener);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void showShare() {
        ShareSDK.initSDK(this);//ShareSDK初始化
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("柴柴柴的测试--TITLE");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("ZAKER----传递最新资讯");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");
        // 启动分享GUI
        oks.show(this);
    }

}
